import swal from 'sweetalert2';
import { Component, OnInit, forwardRef, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';
import { Http, Response } from '@angular/http';

import { CommonComponent } from '../../../../../core/common/common.component';
import { CommonService } from '../../../../../core/common/common.service';
import { ConfigService } from '../../../../../core/common/config.service';
import { TableDictService } from '../../../../../core/common/table-dict.service';
@Component({
  selector: 'ncloud-nodecell-cloud',
  templateUrl: './node-cloud.component.html',
  styles: [``],
  providers: [
    { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NodeCellCloudComponent), multi: true },
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => NodeCellCloudComponent), multi: true }
  ]
})
export class NodeCellCloudComponent extends CommonComponent implements OnInit {
  public interAreas: Array<any> = [];
  @Output() public calculated: EventEmitter<any> = new EventEmitter();
  public select: any = {};
  constructor(private common: CommonService, private http: Http, private tableDict: TableDictService, private config: ConfigService) {
    super();
  }
  ngOnInit() {
    super.ngOnInit();
  }
  writeValue(value) {
    super.writeValue(value);
    if (value) {
      //      放在这里主要是为了初始化省份，也可以在选择节点类型后去初始化
      this.initSelect();
      this.data.slaLevel = '2';
    }
  }
  public addIP(): void {
    this.data.cloud.ipseg.push({});
  }
  public deleteIP(idx: number): void {
    this.data.cloud.ipseg.splice(idx, 1);
  }
  public slaClicked($event: any): void {
    this.data.slaLevel = $event;
    this.getPaymoney();
  }
  public initSelect(): void {
    this.tableDict.get('INTER_AREA').subscribe((data: any) => {
      this.interAreas = data;
    });
    this.tableDict.get('JD_SPEED').subscribe((data: any) => {
      this.select.speed = data;
    });
  }
  public billingCycleChanged(): void {
    const r = /^\+?[1-9][0-9]*$/;
    if (!r.test(this.data.billingCycle)) {
      swal({
        title: '警告！',
        text: '请输入0到36的正整数！',
        type: 'warning',
        confirmButtonColor: '#3085d6',
        confirmButtonText: '确定',
        confirmButtonClass: 'btn btn-success',
      }).then((e: any) => {
        this.data.billingCycle = '';
      }, (dismiss: any) => {
        this.data.billingCycle = '';
      });
    }
    if (this.data.billingCycle > 36) {
      swal({
        title: '警告！',
        text: '周期不能大于36！',
        type: 'warning',
        confirmButtonColor: '#3085d6',
        confirmButtonText: '确定',
        confirmButtonClass: 'btn btn-success',
      }).then((e: any) => {
        this.data.billingCycle = '';
      }, (dismiss: any) => {
        this.data.billingCycle = '';
      });
    } else {
      this.getPaymoney();
    }
  }
  public getPaymoney(): void {
    switch (this.data.discntType) {
      case '0':
        const controls = this.valForm.controls;
        if (controls['data.billingCycle'] && controls['data.billingCycle'].valid && controls['data.bandWidth']
          && controls['data.bandWidth'].valid && controls['data.cloud.interArea'] && controls['data.cloud.interArea'].valid) {
          const url = this.config.get('url') + '?service=ProductService&method=getProdPriceInfo';
          const json = {
            discntId: this.data.discntId, bandWidth: this.data.bandWidth, nodeType: this.data.nodeType,
            interArea: this.data.cloud.interArea, slaLevel: this.data.slaLevel, billingCycle: this.data.billingCycle
          };
          this.http.post(url, json).toPromise().then((response: Response) => {
            const result = response.json();
            if (result && result.code === '0000') {
              this.data.standard = result.info.maxFee / 100;
              this.data.balance = result.info.minFee / 100;
              this.calculated.emit(this.data.standard);
            } else {
              this.data.standard = '';
              this.data.balance = '';
            }
          });
        }
        break;
      case '1':
        break;
      case '2':
        if (this.valForm.controls['data.billingCycle'].valid) {
          this.data.standard = this.data.maxFee * parseInt(this.data.billingCycle, 10) / 100;
          this.data.balance = this.data.minFee * parseInt(this.data.billingCycle, 10) / 100;
        }
        break;
    }
  }
}
